package com.interview.multi.print;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Print01UsingLock {

    private static volatile int state;   // 当前状态值：保证三个线程之间交替打印

    private static Lock lock = new ReentrantLock();

    public Print01UsingLock() {
    }

    private static void printLetter(int targetNum) {
        while(state <= 100){
            lock.lock();
            if(state > 100){
                break;
            }
            if (state % 2 == targetNum) {
                System.out.println(Thread.currentThread().getName() + " " + state++);
            }
            lock.unlock();
        }
    }

    public static void main(String[] args) {

        state = 0;

        new Thread(() -> {
            printLetter(0);
        }, "thread 1").start();

        new Thread(() -> {
            printLetter(1);
        }, "thread 2").start();

    }

}
